package com.vanzo.util;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by tisen on 2018/3/5.
 */

public class LogFileUtil {
    private static String path = "/sdcard/" + "at_log" + ".txt";
    private static Context context;
    private static FileOutputStream outputStream;
    private static OutputStreamWriter writer;
    private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void init() throws FileNotFoundException, UnsupportedEncodingException {
        outputStream = new FileOutputStream(path, false);
        writer = new OutputStreamWriter(outputStream, "utf-8");
    }

    public static void append(StringBuffer stringBuffer) throws IOException {
        writer.write(simpleDateFormat.format(new Date(System.currentTimeMillis()))  + stringBuffer.toString()+"\r\n");
        writer.flush();
    }

    public static void save() throws IOException {
        writer.close();//记得关闭
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        scanIntent.setData(Uri.fromFile(new File(path)));
        context.sendBroadcast(scanIntent);
    }

    public static void setContext(Context context) {
        LogFileUtil.context = context;
    }

    public static void delete() {
        new File(path).delete();
    }
}
